package com.llap.exp190929.util;

import com.llap.exp190929.security.JwtUser;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.DigestUtils;

import java.util.Random;

/**
 * Created by LLAP on 2019/10/14.
 * Copyright (c) 2019 LLAP. All rights reserved.
 */
public class Util {

    private static final String salt = "&%1926***&&%%$$#@";
    private static final Random random = new Random();

    public static String md5(String s) {
        String base = s + "/" + salt;
        return DigestUtils.md5DigestAsHex(base.getBytes());
    }

    public static int randInt() {
        return random.nextInt();
    }

    public static int randInt(int bound) {
        return random.nextInt(bound);
    }

    public static long randLong() {
        return random.nextLong();
    }

    public static JwtUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            if (authentication instanceof AnonymousAuthenticationToken) {
                return null;
            }
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                return (JwtUser) authentication.getPrincipal();
            }
        }
        return null;
    }

    public static boolean isAdmin(JwtUser user) {
        if (user == null) return false;
        return user.getAuthorities().contains(new SimpleGrantedAuthority("admin"));
    }

}
